extends Node2D

var hand_region: Node2D = null
var current_show: Card = null

const SELECTED_CARD_ANIMATE_TIME: float = 0.1
const SELECTED_CARD_ANIMATE_DISTANCE: int = 10
const SELECTED_CARD_ANIMATE_START_SCALE: float = 1.8
const SELECTED_CARD_ANIMATE_END_SCALE: float = 2.0

onready var tween_controller: Tween = get_node('TweenController')

func _ready():
    pass  # Replace with function body.

func _draw():
    if OS.is_debug_build():
        draw_rect(Rect2(-140, -200, 280, 400), Color(0, 1, 0, 1), false)
    pass

func set_hand_region(hr: Node2D) -> void:
    if hand_region != null:
        hand_region.disconnect('card_selected', self, '_on_hand_card_selected')
        hand_region.disconnect('card_unselected', self, '_on_hand_card_unselected')
        hand_region = null
    hand_region = hr
    hand_region.connect('card_selected', self, '_on_hand_card_selected')
    hand_region.connect('card_unselected', self, '_on_hand_card_unselected')
    pass


func _on_hand_card_selected(pos: int, c: Card) -> void:
    # 清理当前显示的卡牌
    if current_show != null:
        current_show.queue_free()
        pass

    # 创建新节点并调整显示
    current_show = CardFactory.copy_card(c)
    current_show.set_position(Vector2(0, 0))
    current_show.set_scale(Vector2(1.8, 1.8))
    add_child(current_show)

    tween_controller.interpolate_property(
        current_show,
        'position',
        Vector2(0, 0),
        Vector2(0, - SELECTED_CARD_ANIMATE_DISTANCE),
        SELECTED_CARD_ANIMATE_TIME,
        Tween.TRANS_LINEAR,
        Tween.EASE_OUT)

    tween_controller.interpolate_property(
        current_show,
        'scale',
        Vector2(SELECTED_CARD_ANIMATE_START_SCALE, SELECTED_CARD_ANIMATE_START_SCALE),
        Vector2(SELECTED_CARD_ANIMATE_END_SCALE, SELECTED_CARD_ANIMATE_END_SCALE),
        SELECTED_CARD_ANIMATE_TIME,
        Tween.TRANS_LINEAR,
        Tween.EASE_OUT)

    tween_controller.start()

    # 根据屏幕和选中的卡牌调整位置
    var card_global_x: int = int(c.global_position.x)
    var size: Vector2 = get_viewport().get_size()
    position = Vector2(card_global_x, size.y / 2)

    # 把原先的卡牌设置成不可见
    c.modulate = Color(1.0, 1.0, 1.0, 0)

    pass

func _on_hand_card_unselected(pos: int, c: Card) -> void:
    # 清理当前显示的卡牌
    if current_show != null:
        remove_child(current_show)
        pass
    c.modulate = Color(1.0, 1.0, 1.0, 1.0)
    pass
